import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../models/important_day.dart';
import '../providers/important_days_provider.dart';

class AddImportantDayScreen extends StatefulWidget {
  final ImportantDay? editingDay;
  
  const AddImportantDayScreen({super.key, this.editingDay});

  @override
  State<AddImportantDayScreen> createState() => _AddImportantDayScreenState();
}

class _AddImportantDayScreenState extends State<AddImportantDayScreen> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  
  DateTime _selectedDate = DateTime.now();
  String _selectedCategory = 'anniversary';
  String _selectedEmoji = '💕';
  
  final List<Map<String, dynamic>> _categories = [
    {'id': 'anniversary', 'name': '纪念日', 'emoji': '💕', 'color': Colors.pink},
    {'id': 'birthday', 'name': '生日', 'emoji': '🎂', 'color': Colors.blue},
    {'id': 'valentine', 'name': '情人节', 'emoji': '💝', 'color': Colors.red},
    {'id': 'festival', 'name': '节日', 'emoji': '🌟', 'color': Colors.purple},
    {'id': 'date', 'name': '约会', 'emoji': '🌹', 'color': Colors.orange},
    {'id': 'other', 'name': '其他', 'emoji': '✨', 'color': Colors.green},
  ];
  
  final List<String> _emojis = [
    '💕', '🎂', '💝', '🌟', '🌹', '✨',
    '🎉', '💖', '🎈', '🌺', '🎁', '💐',
    '🌙', '⭐', '🦋', '🌈', '🍰', '🎊'
  ];

  @override
  void initState() {
    super.initState();
    if (widget.editingDay != null) {
      _titleController.text = widget.editingDay!.title;
      _descriptionController.text = widget.editingDay!.description;
      _selectedDate = widget.editingDay!.date;
      _selectedCategory = widget.editingDay!.category;
      _selectedEmoji = widget.editingDay!.emoji;
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isEditing = widget.editingDay != null;
    
    return Container(
      height: MediaQuery.of(context).size.height * 0.9,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          automaticallyImplyLeading: false,
          toolbarHeight: 60,
          flexibleSpace: Container(
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            child: SafeArea(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.close, color: Colors.grey),
                      onPressed: () => Navigator.pop(context),
                    ),
                    Expanded(
                      child: Text(
                        isEditing ? '编辑重要日子' : '添加重要日子',
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                          color: Colors.black87,
                          fontWeight: FontWeight.w600,
                          fontSize: 18,
                        ),
                      ),
                    ),
                    TextButton(
                      onPressed: _saveImportantDay,
                      child: Text(
                        isEditing ? '保存' : '完成',
                        style: const TextStyle(
                          color: Colors.pink,
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        body: Container(
          decoration: BoxDecoration(
            color: Colors.grey.shade50,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          child: Form(
            key: _formKey,
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 预览卡片
                  _buildPreviewCard(),
                  
                  const SizedBox(height: 24),
                  
                  // 基本信息
                  _buildSectionTitle('基本信息'),
                  const SizedBox(height: 12),
                  _buildTitleField(),
                  const SizedBox(height: 16),
                  _buildDescriptionField(),
                  
                  const SizedBox(height: 24),
                  
                  // 日期选择
                  _buildSectionTitle('选择日期'),
                  const SizedBox(height: 12),
                  _buildDateSelector(),
                  
                  const SizedBox(height: 24),
                  
                  // 分类选择
                  _buildSectionTitle('选择分类'),
                  const SizedBox(height: 12),
                  _buildCategorySelector(),
                  
                  const SizedBox(height: 24),
                  
                  // 表情选择
                  _buildSectionTitle('选择表情'),
                  const SizedBox(height: 12),
                  _buildEmojiSelector(),
                  
                  const SizedBox(height: 40),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPreviewCard() {
    final daysUntil = _selectedDate.difference(DateTime.now()).inDays;
    final isPast = daysUntil < 0;
    
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: isPast 
            ? [Colors.grey.shade100, Colors.grey.shade200]
            : [Colors.pink.shade50, Colors.pink.shade100],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: isPast ? Colors.grey.shade300 : Colors.pink.shade200,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                _selectedEmoji,
                style: const TextStyle(fontSize: 32),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _titleController.text.isEmpty ? '重要日子标题' : _titleController.text,
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: isPast ? Colors.grey.shade600 : Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      _descriptionController.text.isEmpty ? '添加一些描述...' : _descriptionController.text,
                      style: TextStyle(
                        fontSize: 14,
                        color: isPast ? Colors.grey.shade500 : Colors.grey.shade600,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: isPast ? Colors.grey.shade200 : Colors.white.withOpacity(0.8),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              daysUntil == 0 
                ? '今天'
                : daysUntil > 0 
                  ? '还有 $daysUntil 天'
                  : '已过去 ${-daysUntil} 天',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                color: isPast ? Colors.grey.shade600 : Colors.pink.shade700,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.w600,
        color: Colors.black87,
      ),
    );
  }

  Widget _buildTitleField() {
    return TextFormField(
      controller: _titleController,
      decoration: InputDecoration(
        hintText: '输入重要日子的标题',
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.all(16),
      ),
      validator: (value) {
        if (value == null || value.trim().isEmpty) {
          return '请输入标题';
        }
        return null;
      },
      onChanged: (value) => setState(() {}),
    );
  }

  Widget _buildDescriptionField() {
    return TextFormField(
      controller: _descriptionController,
      maxLines: 3,
      decoration: InputDecoration(
        hintText: '添加一些描述或备注...',
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.all(16),
      ),
      onChanged: (value) => setState(() {}),
    );
  }

  Widget _buildDateSelector() {
    return GestureDetector(
      onTap: _selectDate,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Row(
          children: [
            Icon(Icons.calendar_today, color: Colors.pink.shade400),
            const SizedBox(width: 12),
            Text(
              DateFormat('yyyy年MM月dd日').format(_selectedDate),
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
            const Spacer(),
            Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey.shade400),
          ],
        ),
      ),
    );
  }

  Widget _buildCategorySelector() {
    return Wrap(
      spacing: 12,
      runSpacing: 12,
      children: _categories.map((category) {
        final isSelected = _selectedCategory == category['id'];
        return GestureDetector(
          onTap: () {
            setState(() {
              _selectedCategory = category['id'];
              _selectedEmoji = category['emoji'];
            });
          },
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: isSelected ? category['color'].withOpacity(0.1) : Colors.white,
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: isSelected ? category['color'] : Colors.grey.shade200,
                width: isSelected ? 2 : 1,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(category['emoji'], style: const TextStyle(fontSize: 18)),
                const SizedBox(width: 8),
                Text(
                  category['name'],
                  style: TextStyle(
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                    color: isSelected ? category['color'] : Colors.black87,
                  ),
                ),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildEmojiSelector() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Wrap(
        spacing: 12,
        runSpacing: 12,
        children: _emojis.map((emoji) {
          final isSelected = _selectedEmoji == emoji;
          return GestureDetector(
            onTap: () => setState(() => _selectedEmoji = emoji),
            child: Container(
              width: 48,
              height: 48,
              decoration: BoxDecoration(
                color: isSelected ? Colors.pink.shade50 : Colors.transparent,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected ? Colors.pink.shade300 : Colors.transparent,
                  width: 2,
                ),
              ),
              child: Center(
                child: Text(emoji, style: const TextStyle(fontSize: 24)),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime(2030),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary: Colors.pink.shade400,
              onPrimary: Colors.white,
              surface: Colors.white,
              onSurface: Colors.black87,
            ),
          ),
          child: child!,
        );
      },
    );
    
    if (picked != null && picked != _selectedDate) {
      setState(() => _selectedDate = picked);
    }
  }

  void _saveImportantDay() {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    final provider = Provider.of<ImportantDaysProvider>(context, listen: false);
    
    if (widget.editingDay != null) {
      // 编辑模式
      final updatedDay = ImportantDay(
        id: widget.editingDay!.id,
        title: _titleController.text.trim(),
        description: _descriptionController.text.trim(),
        date: _selectedDate,
        category: _selectedCategory,
        emoji: _selectedEmoji,
      );
      provider.updateImportantDay(updatedDay);
    } else {
      // 新增模式
      final newDay = ImportantDay(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        title: _titleController.text.trim(),
        description: _descriptionController.text.trim(),
        date: _selectedDate,
        category: _selectedCategory,
        emoji: _selectedEmoji,
      );
      provider.addImportantDay(newDay);
    }

    // 显示成功提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(widget.editingDay != null ? '重要日子已更新' : '重要日子已添加'),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );

    Navigator.pop(context);
  }
}